package com.huiying.service.Impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.huiying.constant.MessageConstant;
import com.huiying.context.BaseContext;
import com.huiying.entity.dto.DemandDTO;
import com.huiying.entity.dto.DemandPageQueryDTO;
import com.huiying.entity.entity.*;
import com.huiying.entity.result.PageResult;
import com.huiying.entity.vo.DemandPageVO;
import com.huiying.entity.vo.DemandVO;
import com.huiying.entity.vo.UserVO;
import com.huiying.mapper.*;
import com.huiying.service.CommonService;
import com.huiying.service.DemandService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author: lsh
 * @Date: 2024/10/29/10:54
 * @Description: 需求单实现类
 */
@Service
@Slf4j
public class DemandServiceImpl implements DemandService {

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private DemandMapper demandMapper;

    @Autowired
    private ContentMapper contentMapper;

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LikeMapper likeMapper;

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private BidMapper bidMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ReadMapper readMapper;

    @Autowired
    private FollowMapper followMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private CommonService commonService;

    private static final String DEMAND = "0";

    /**
     * 新增需求单
     * @param demandDTO
     * @return: void
     */
    @Override
    @Transactional
    public void add(DemandDTO demandDTO) {
        Long userId = BaseContext.getCurrentId();

        UserVO user = userMapper.getById(userId);

        // 判断用户是否已经实名认证
        String isAuthenticated = user.getName() != null && user.getIdNumber() != null ? "1" : "0";

        // 创建需求单对象，复制DTO中的内容
        Demand demand = new Demand();
        demand.setDemandType(demandDTO.getDemandType());
        BeanUtils.copyProperties(demandDTO, demand);
        demand.setUserId(userId);
        demand.setGender(user.getGender());
        demand.setUsername(user.getUsername());
        demand.setIsAuthenticated(isAuthenticated);

        // 在数据库中插入新的需求单
        demandMapper.insert(demand);
        Long id = demand.getId();

        // 获取标签列表，去重后插入内容标签关系表
        List<ContentTag> contentTags = getContentTags(demandDTO, id);

        // 批量插入标签数据
        if (!contentTags.isEmpty()) {
            contentMapper.addContentTags(contentTags);
        }

        // 将需求单的图片插入图片表
        List<Image> imageList = getImages(demandDTO, id);

        // 批量插入图片数据
        if (!imageList.isEmpty()) {
            imageMapper.addContentImages(imageList);
        }
    }

    /**
     * 获取标签列表并去重
     * @param demandDTO
     * @param id
     * @return: java.util.List<com.fx.entity.Image>
     */
    private static List<Image> getImages(DemandDTO demandDTO, Long id) {
        List<String> images = demandDTO.getImages();
        List<Image> imageList = new ArrayList<>();
        Set<String> existingImageUrls = new HashSet<>(); // 用 Set 来避免重复插入相同的图片

        images.forEach(imageUrl -> {
            if (!existingImageUrls.contains(imageUrl)) {
                existingImageUrls.add(imageUrl);
                Image image = new Image();
                image.setImageURL(imageUrl);
                image.setDemandId(id);
                image.setCreateTime(LocalDateTime.now());
                imageList.add(image);
            }
        });
        return imageList;
    }

    /**
     * 获取图片列表并去重
     * @param demandDTO
     * @param id
     * @return: java.util.List<com.fx.entity.ContentTag>
     */
    private static List<ContentTag> getContentTags(DemandDTO demandDTO, Long id) {
        List<Tag> tags = demandDTO.getTags();
        List<ContentTag> contentTags = new ArrayList<>();
        Set<Long> existingTagIds = new HashSet<>();  // 用 Set 来去重

        tags.forEach(tag -> {
            if (!existingTagIds.contains(tag.getId())) {
                existingTagIds.add(tag.getId());
                ContentTag contentTag = new ContentTag();
                contentTag.setTagId(tag.getId());
                contentTag.setContentId(id);
                contentTag.setContentType(DEMAND);
                contentTag.setCreateTime(LocalDateTime.now());
                contentTags.add(contentTag);
            }
        });
        return contentTags;
    }

    /**
     * 需求单分页查询
     * @param demandPageQueryDTO
     * @return: com.fx.result.PageResult
     */
    @Override
    public PageResult pageQuery(DemandPageQueryDTO demandPageQueryDTO) {
        PageHelper.startPage(demandPageQueryDTO.getPage(), demandPageQueryDTO.getPageSize());

        Page<DemandPageVO> page = demandMapper.pageQuery(demandPageQueryDTO);

        long total = page.getTotal();
        List<DemandPageVO> result = page.getResult();

        return new PageResult(total,result);
    }

    /**
     * 用户发送接单请求
     * @param bid
     * @return: void
     */
    @Override
    public Boolean bid(Bid bid) {
        Long userId = BaseContext.getCurrentId();
        bid.setUserId(userId);
        Bid bid1 = bidMapper.getByUserIdWithDemandId(bid);
        if (bid1 == null) {
            bidMapper.insert(bid);
            return true;
        }
        return false;
    }

    /**
     * 根据id查询需求单
     * @param demandId
     * @return: com.fx.vo.DemandVO
     */
    @Transactional
    @Override
    public DemandVO getById(Long demandId) {
        Long userId = BaseContext.getCurrentId();

        //在阅读表中添加阅读记录
        Read read = Read.builder()
                .itemId(demandId)
                .itemType(DEMAND)
                .userId(userId)
                .readTime(LocalDateTime.now())
                .build();

        readMapper.insert(read);

        DemandVO demandVO = demandMapper.getDemandInfoById(demandId,userId);

        //查询用户是否已经互相关注
        String isFollow = "0";
        if (userId.equals(demandVO.getUserId())){
            isFollow = "2";
        }else {
            Follow follow = followMapper.getFollowByUserId(userId,demandVO.getUserId());
            if (follow != null){
                isFollow = "1";
            }
        }

        //获取点赞数
        long likes = commonService.countLikes(demandId,DEMAND);
        log.info("点赞数{}",likes);

        demandVO.setLikeCount(likes);
        demandVO.setIsFollow(isFollow);

        return demandVO;
    }

    /**
     * 修改需求单
     * @param demandDTO 需求单数据传输对象
     * @return: void
     */
    @Override
    @Transactional
    public void updateDemand(DemandDTO demandDTO) {
        //删除原有标签记录
        tagMapper.deleteByContentId(demandDTO.getId(),DEMAND);
        //删除原有图片
        imageMapper.deleteByDemandId(demandDTO.getId());

        //更新需求单基本信息
        demandMapper.update(demandDTO);

        List<ContentTag> contentTags = new ArrayList<>();
        List<Image> images = new ArrayList<>();

        // 3. 插入新的标签和图片
        if (demandDTO.getTags() != null && !demandDTO.getTags().isEmpty()) {
            demandDTO.getTags().forEach(tag -> {
                ContentTag contentTag = ContentTag.builder()
                        .contentId(demandDTO.getId())
                        .contentType(DEMAND)
                        .tagId(tag.getId())
                        .createTime(LocalDateTime.now())
                        .build();
                contentTags.add(contentTag);
            });
            contentMapper.addContentTags(contentTags);
        }

        if (demandDTO.getImages() != null && !demandDTO.getImages().isEmpty()) {
            demandDTO.getImages().forEach(image->{
                Image image1 = Image.builder()
                        .demandId(demandDTO.getId())
                        .imageURL(image)
                        .createTime(LocalDateTime.now())
                        .build();
                images.add(image1);
            });
            imageMapper.addContentImages(images);
        }

    }

    /**
     * 删除需求单
     * @param demandId 需求单数据传输对象
     * @return: void
     */
    @Transactional
    public void deleteDemand(Long demandId) {
        Demand demand = demandMapper.getById(demandId);
        if (demand == null){
            throw new RuntimeException(MessageConstant.DEMAND_IS_NULL);
        }

        // 删除接单表中相关记录
        bidMapper.deleteByDemandId(demandId);

        //删除需求单的相关标签记录
        tagMapper.deleteByContentId(demandId,DEMAND);

        //删除需求单的相关图片记录
        imageMapper.deleteByDemandId(demandId);

        // 删除对应的缓存
        redisTemplate.delete("demand" + demandId);
        //删除用户对该需求单的所有点赞
        likeMapper.deleteByDemandId(demandId,DEMAND);

        //删除用户删除收藏
        favoriteMapper.deleteByContentId(demandId,DEMAND);

        //删除用户对该需求单的浏览记录
        readMapper.deleteByItemId(demandId,DEMAND);

        //删除该需求单的所有评论
        commentMapper.deleteByItemId(demandId,DEMAND);

        //删除需求单本身
        demandMapper.deleteById(demandId);
    }
}
